import {Component, OnDestroy, OnInit, ViewChild} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {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 "../utils/entities/stakeholder";
import {StakeholderService} from "../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 "../library/sharedComponents/sidebar/layout.service";
import {IndicatorUtils} from "../utils/indicator-utils";

declare var UIkit;

@Component({
  selector: 'stakeholder',
  templateUrl: './stakeholder.component.html',
})
export class StakeholderComponent implements OnInit, OnDestroy {
  public subscriptions: any[] = [];
  public loading: boolean = true;
  public errorCodes: ErrorCodes;
  public stakeholder: Stakeholder;
  public analysisOpen: boolean = true;
  private errorMessages: ErrorMessagesComponent;
  public topicFb: FormGroup;
  public indicatorUtils: IndicatorUtils = new IndicatorUtils();
  public element: any;
  public index: number;
  properties: EnvProperties;

  @ViewChild('deleteTopicModal') deleteTopicModal: AlertModal;

  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private title: Title,
    private layoutService: LayoutService,
    private fb: FormBuilder,
    private stakeholderService: StakeholderService) {
    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.topicFb = null;
            this.title.setTitle(stakeholder.index_name);
          }
        }));
      });
  }

  public ngOnDestroy() {
    this.subscriptions.forEach(value => {
      if (value instanceof Subscriber) {
        value.unsubscribe();
      }
    });
  }

  public show(element) {
    UIkit.drop(element).show();
  }

  public hide(element) {
    UIkit.drop(element).hide();
  }

  get open(): boolean {
    return this.layoutService.open;
  }

  public toggleOpen(event = null) {
    if (!event) {
      this.layoutService.setOpen(!this.open);
    } else if (event && event['value'] === true) {
      this.layoutService.setOpen(false);
    }
  }

  private buildTopic(topic: Topic) {
    this.topicFb = 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),
      isActive: this.fb.control(topic.isActive),
      isPublic: this.fb.control(topic.isPublic),
      isDefault: this.fb.control(topic.isDefault),
      categories: this.fb.control(topic.categories)
    });
  }

  public saveTopicOpen(element, index = -1) {
    if (element.className.indexOf('uk-open') !== -1) {
      this.hide(element);
    } else {
      if (index === -1) {
        this.buildTopic(new Topic(null, null, null, true, true, false));
      } else {
        this.buildTopic(this.stakeholder.topics[index]);
      }
      this.show(element);
    }
  }

  public saveTopic(element, index = -1) {
    if (!this.topicFb.invalid) {
      if (!this.topicFb.value.alias) {
        this.topicFb.value.alias = this.topicFb.value.name.toLowerCase().trim();
      }
      if (index === -1) {
        this.save('Topic has been successfully created', element);
      } else {
        this.save('Topic has been successfully saved', element, index);
      }
    }
  }

  public deleteTopicOpen(name: string, element, index: number) {
    this.element = element;
    this.index = index;
    this.deleteTopicModal.alertTitle = 'Delete ' + name;
    this.deleteTopicModal.cancelButtonText = 'No';
    this.deleteTopicModal.okButtonText = 'Yes';
    this.deleteTopicModal.message = 'This topic will permanently be deleted. Are you sure you want to proceed?';
    this.deleteTopicModal.open();
  }

  private save(message: string, element, index: number = -1) {
    let path = [this.stakeholder._id];
    this.stakeholderService.saveElement(this.properties.monitorServiceAPIURL, this.topicFb.value, path).subscribe(topic => {
      if (index === -1) {
        this.stakeholder.topics.push(topic);
      } else {
        this.stakeholder.topics[index] = topic;
      }
      this.stakeholderService.setStakeholder(this.stakeholder);
      UIkit.notification(message, {
        status: 'success',
        timeout: 3000000,
        pos: 'top-left'
      });
      this.hide(element);
    }, error => {
      UIkit.notification(error.error.message, {
        status: 'danger',
        timeout: 3000,
        pos: 'top-left'
      });
      this.hide(element);
    });
  }

  deleteTopic() {
    let path = [
      this.stakeholder._id,
      this.stakeholder.topics[this.index]._id
    ];
    this.stakeholderService.deleteElement(this.properties.monitorServiceAPIURL, path).subscribe(() => {
      this.stakeholder.topics.splice(this.index, 1);
      this.stakeholderService.setStakeholder(this.stakeholder);
      UIkit.notification('Topic has been successfully deleted', {
        status: 'success',
        timeout: 3000,
        pos: 'top-left'
      });
      this.hide(this.element);
    }, error => {
      UIkit.notification(error.error.message, {
        status: 'danger',
        timeout: 3000,
        pos: 'top-left'
      });
      this.hide(this.element);
    });
  }
}
