import {Component, OnDestroy, OnInit, ViewChild} from '@angular/core';
import {Location} from '@angular/common';
import {ActivatedRoute, Router} from '@angular/router';
import {DomSanitizer, Title} from '@angular/platform-browser';
import {EnvProperties} from '../openaireLibrary/utils/properties/env-properties';

import {ErrorCodes} from '../openaireLibrary/utils/properties/errorCodes';
import {ErrorMessagesComponent} from '../openaireLibrary/utils/errorMessages.component';
import {Stakeholder, Topic} from "../openaireLibrary/monitor/entities/stakeholder";
import {StakeholderService} from "../openaireLibrary/monitor/services/stakeholder.service";
import {HelperFunctions} from "../openaireLibrary/utils/HelperFunctions.class";
import {AlertModal} from "../openaireLibrary/utils/modal/alert";
import {Subscriber} from "rxjs";
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {LayoutService} from "../openaireLibrary/dashboard/sharedComponents/sidebar/layout.service";
import {IndicatorUtils, StakeholderUtils} from "../utils/indicator-utils";
import {IDeactivateComponent} from "../openaireLibrary/utils/can-exit.guard";

declare var UIkit;

@Component({
  selector: 'stakeholder',
  templateUrl: './stakeholder.component.html',
})
export class StakeholderComponent implements OnInit, OnDestroy, IDeactivateComponent {
  public subscriptions: any[] = [];
  public loading: boolean = true;
  public errorCodes: ErrorCodes;
  public stakeholder: Stakeholder;
  public analysisOpen: boolean = true;
  private errorMessages: ErrorMessagesComponent;
  public form: FormGroup;
  public stakeholderUtils: StakeholderUtils = new StakeholderUtils();
  public indicatorUtils: IndicatorUtils = new IndicatorUtils();
  public index: number = -1;
  properties: EnvProperties;
  
  @ViewChild('deleteModal') deleteModal: AlertModal;
  @ViewChild('editModal') editModal: AlertModal;
  public topicChildrenActionOnDelete: string;

  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private title: Title,
    private layoutService: LayoutService,
    private fb: FormBuilder,
    private stakeholderService: StakeholderService, private sanitizer: DomSanitizer, private _location: Location) {
    this.errorCodes = new ErrorCodes();
    this.errorMessages = new ErrorMessagesComponent();
  }
  
  public ngOnInit() {
    this.route.data
      .subscribe((data: { envSpecific: EnvProperties }) => {
        this.properties = data.envSpecific;
        this.subscriptions.push(this.stakeholderService.getStakeholderAsObservable().subscribe(stakeholder => {
          if (stakeholder) {
            this.stakeholder = HelperFunctions.copy(stakeholder);
            this.form = null;
            this.title.setTitle(stakeholder.name);
          }
        }));
      });
  }
  
  public ngOnDestroy() {
  }

  canExit():boolean {
    this.subscriptions.forEach(value => {
      if (value instanceof Subscriber) {
        value.unsubscribe();
      }
    });
    this.stakeholderService.setStakeholder(this.stakeholder);
    return true;
  }
  
  hide(element: any) {
    UIkit.dropdown(element).hide();
  }
  
  get open(): boolean {
    return this.layoutService.open;
  }
  
  private buildTopic(topic: Topic) {
    let topics = this.stakeholder.topics.filter(element => element._id !== topic._id);
    this.form = this.fb.group({
      _id: this.fb.control(topic._id),
      name: this.fb.control(topic.name, Validators.required),
      description: this.fb.control(topic.description),
      alias: this.fb.control(topic.alias, [
          Validators.required,
          this.stakeholderUtils.aliasValidator(topics)
        ]
      ),
      isActive: this.fb.control(topic.isActive),
      isPublic: this.fb.control(topic.isPublic),
      defaultId: this.fb.control(topic.defaultId),
      categories: this.fb.control(topic.categories),
      icon: this.fb.control(topic.icon)
    });
    this.subscriptions.push(this.form.get('name').valueChanges.subscribe(value => {
      let i = 1;
      value = this.stakeholderUtils.generateAlias(value);
      this.form.controls['alias'].setValue(value);
      while (this.form.get('alias').invalid) {
        this.form.controls['alias'].setValue(value + i);
        i++;
      }
    }));
  }
  
  public editTopicOpen(index = -1) {
    this.index = index;
    if (index === -1) {
      this.buildTopic(new Topic(null, null, null, true, true));
    } else {
      this.buildTopic(this.stakeholder.topics[index]);
    }
    this.editModal.cancelButtonText = 'Cancel';
    this.editModal.okButtonLeft = false;
    this.editModal.alertMessage = false;
    if (index === -1) {
      this.editModal.alertTitle = 'Create a new topic';
      this.editModal.okButtonText = 'Create';
    } else {
      this.editModal.alertTitle = 'Edit topic\'s information ';
      this.editModal.okButtonText = 'Save';
    }
    this.editModal.open();
  }
  
  public saveTopic(index = -1) {
    if (!this.form.invalid) {
      if (index === -1) {
        this.save('Topic has been successfully created');
      } else {
        this.save('Topic has been successfully saved', index);
      }
    }
  }
  
  public deleteTopicOpen(index: number, childrenAction: string = null) {
    this.topicChildrenActionOnDelete = null;
    if(childrenAction == "delete") {
      this.topicChildrenActionOnDelete = childrenAction;
    } else if(childrenAction == "disconnect") {
      this.topicChildrenActionOnDelete = childrenAction;
    }

    this.index = index;
    this.deleteModal.alertTitle = 'Delete topic';
    this.deleteModal.cancelButtonText = 'No';
    this.deleteModal.okButtonText = 'Yes';
    this.deleteModal.open();
  }
  
  private save(message: string, index: number = -1) {
    let path = [this.stakeholder._id];
    this.stakeholderService.saveElement(this.properties.monitorServiceAPIURL, this.form.value, path).subscribe(topic => {
      if (index === -1) {
        this.stakeholder.topics.push(topic);
      } else {
        this.stakeholder.topics[index] = topic;
      }
      UIkit.notification(message, {
        status: 'success',
        timeout: 3000,
        pos: 'top-left'
      });
    }, error => {
      UIkit.notification(error.error.message, {
        status: 'danger',
        timeout: 3000,
        pos: 'top-left'
      });
    });
  }
  
  deleteTopic() {
    let path = [
      this.stakeholder._id,
      this.stakeholder.topics[this.index]._id
    ];
    this.stakeholderService.deleteElement(this.properties.monitorServiceAPIURL, path, this.topicChildrenActionOnDelete).subscribe(() => {
      this.stakeholder.topics.splice(this.index, 1);
      this.index = -1;
      UIkit.notification('Topic has been successfully deleted', {
        status: 'success',
        timeout: 3000,
        pos: 'top-left'
      });
    }, error => {
      UIkit.notification(error.error.message, {
        status: 'danger',
        timeout: 3000,
        pos: 'top-left'
      });
    });
  }
  
  toggleTopicStatus(topic: Topic) {
    let path = [
      this.stakeholder._id,
      topic._id
    ];
    this.stakeholderService.toggleStatus(this.properties.monitorServiceAPIURL, path).subscribe(isActive => {
      topic.isActive = isActive;
      UIkit.notification('Topic has been successfully changed to ' + (isActive ? 'active' : 'inactive'), {
        status: 'success',
        timeout: 3000,
        pos: 'top-left'
      });
    }, error => {
      UIkit.notification(error.error.message, {
        status: 'danger',
        timeout: 3000,
        pos: 'top-left'
      });
    });
  }
  
  toggleTopicAccess(topic: Topic) {
    let path = [
      this.stakeholder._id,
      topic._id
    ];
    this.stakeholderService.toggleAccess(this.properties.monitorServiceAPIURL, path).subscribe(isPublic => {
      topic.isPublic = isPublic;
      UIkit.notification('Topic has been successfully changed to ' + (isPublic?'public':'private'), {
        status: 'success',
        timeout: 3000,
        pos: 'top-left'
      });
    }, error => {
      UIkit.notification(error.error.message, {
        status: 'danger',
        timeout: 3000,
        pos: 'top-left'
      });
    });
  }
  satinizeHTML(html){
    return this.sanitizer.bypassSecurityTrustHtml(html);
  }
}
