import {Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import {ActivatedRoute, Router} from "@angular/router";
import {HelpContentService} from "../../../services/help-content.service";
import {FormArray, FormGroup, UntypedFormBuilder, UntypedFormGroup, ValidatorFn, Validators} from "@angular/forms";
import {Page} from "../../../utils/entities/adminTool/page";
import {EnvProperties} from '../../../utils/properties/env-properties';
import {HelperFunctions} from "../../../utils/HelperFunctions.class";
import {Subscriber} from "rxjs";
import {properties} from "../../../../../environments/environment";
import {PortalUtils} from "../../portal/portalHelper";
import {AlertModal} from "../../../utils/modal/alert";
import {Option} from "../../../sharedComponents/input/input.component";
import {Title} from "@angular/platform-browser";
import {ClearCacheService} from "../../../services/clear-cache.service";
import {NotificationHandler} from "../../../utils/notification-handler";
import {PluginsService} from "../../../services/plugins.service";
import {PluginTemplate} from "../../../utils/entities/adminTool/pluginTemplate";
import {StringUtils} from "../../../utils/string-utils.class";
import {PluginUtils} from "../utils/pluginUtils";
import {PluginEditEvent} from "../utils/base-plugin.form.component";

@Component({
  selector: 'plugin-templates',
  templateUrl: './pluginTemplates.component.html',
})
export class PluginTemplatesComponent implements OnInit {
  @ViewChild('editModal') editModal: AlertModal;
  @ViewChild('deleteModal') deleteModal: AlertModal;
  public templatesByPlacement: Map<string,PluginTemplate[]> = new Map();
  public templateForm: UntypedFormGroup;
  urlValidator: ValidatorFn = StringUtils.urlValidator;
  private searchText: RegExp = new RegExp('');
  public keyword: string = "";
  public properties: EnvProperties = properties;
  public formPages: Page[] = [];
  public showLoading: boolean = true;
  public filterForm: UntypedFormGroup;
  private subscriptions: any[] = [];
  public allPages: Option[] = [];
  public allPagesByPortal: Map<string, Option[]> = new Map();
  public pluginUtils = new PluginUtils();
  public portalUtils: PortalUtils = new PortalUtils();
  private selectedTemplate: PluginTemplate;
  public selectedPageId: string;
  public selectedPortalPid: string;
  public page: Page;
  editSubmenuOpen = false;
  constructor(private element: ElementRef, private route: ActivatedRoute, private _router: Router,
              private title: Title, private _helpContentService: HelpContentService,
              private _pluginsService: PluginsService, private _fb: UntypedFormBuilder,
              private _clearCacheService: ClearCacheService) {
  }

  ngOnInit() {
    this.title.setTitle('Administrator Dashboard | Classes');
    this.filterForm = this._fb.group({
      keyword: [''],
      position: ['all', Validators.required]
    });
    this.subscriptions.push(this.filterForm.get('keyword').valueChanges.subscribe(value => {
      this.searchText = new RegExp(value, 'i');
    }));

    this.subscriptions.push(this.route.queryParams.subscribe(params => {
      HelperFunctions.scroll();
      this.selectedPageId = params['pageId'];
      this.selectedPortalPid = params['portalPid'];
      if (this.selectedPageId) {
        this.getPage(this.selectedPageId);
        this.getTemplates(this.selectedPageId);

      } else {
        this.getPages();
        this.getTemplates();

      }
    }));

  }

  ngOnDestroy(): void {
    this.subscriptions.forEach(value => {
      if (value instanceof Subscriber) {
        value.unsubscribe();
      } else if (value instanceof Function) {
        value();
      }
    });
  }

  getPage(pageId: string) {
    this.showLoading = true;
    this.subscriptions.push(this._helpContentService.getPageById(pageId, this.properties.adminToolsAPIURL).subscribe(
      page => {
        this.page = page;
        this.allPages = [];
        this.allPagesByPortal = new Map();
        let option = {
          label: page.name + " [" + page.portalType + "]",
          value: page
        };
        this.allPages.push(option);
        this.allPagesByPortal.set(page.portalType, [])
        this.allPagesByPortal.get(page.portalType).push(option)
      },
      error => this.handleError('System error retrieving page', error)));
  }

  getTemplates(pageId = null) {
    this.showLoading = true;
    this.subscriptions.push(this._pluginsService.getPluginTemplates(this.properties.adminToolsAPIURL, pageId).subscribe(
      templates => {
        for(let pos of this.pluginUtils.placementsOptions){
          this.templatesByPlacement.set(pos.value,[]);
        }
        for(let template of templates){
          template.object = PluginUtils.initializeObjectAndCompare(template.code,template.object)
          this.templatesByPlacement.get(template.placement).push(template);
        }
        let self = this;
        this.showLoading = false;
      },
      error => this.handleError('System error retrieving classes', error)));
  }

  private deleteFromArray(template:PluginTemplate): void {

    let i = this.templatesByPlacement.get(template.placement).findIndex(_ => _._id == template._id);
    this.templatesByPlacement.get(template.placement).splice(i, 1);

  }

  public confirmDelete(template:PluginTemplate) {
    this.selectedTemplate = template;
    this.confirmModalOpen();
  }


  private confirmModalOpen() {
    this.deleteModal.alertTitle = "Delete Confirmation";
    this.deleteModal.message = "Are you sure you want to delete the selected template(s)?";
    this.deleteModal.okButtonText = "Yes";
    this.deleteModal.open();
  }

  public confirmedDelete() {
    this.showLoading = true;
    this.subscriptions.push(this._pluginsService.deletePluginTemplate(this.selectedTemplate._id, this.properties.adminToolsAPIURL).subscribe(
      _ => {
        this.deleteFromArray(this.selectedTemplate);
        NotificationHandler.rise('Template have been <b>successfully deleted</b>');
        this.showLoading = false;
        // this._clearCacheService.clearCache("Template id deleted");
      },
      error => this.handleUpdateError('System error deleting the selected Template', error)
    ));
  }

  public edit(pluginTemplate) {
    this.selectedTemplate = JSON.parse(JSON.stringify(pluginTemplate)); // deep copy object with nested objects
    this.templateForm = this._fb.group({
      _id: this._fb.control(pluginTemplate._id),
      name: this._fb.control(pluginTemplate.name),
      page: this._fb.control(this.getPageById(pluginTemplate.page)),
      portalType: this._fb.control(pluginTemplate.portalType, Validators.required),

      code: this._fb.control(pluginTemplate.code, Validators.required),
      description: this._fb.control(pluginTemplate.description),
      plan: this._fb.control(pluginTemplate.plan, Validators.required),
      placement: this._fb.control(pluginTemplate.placement, Validators.required),
      order: this._fb.control(pluginTemplate.order),
      portalSpecific: this._fb.control(pluginTemplate.portalSpecific?pluginTemplate.portalSpecific.join(','):''),
      defaultIsActive: this._fb.control(pluginTemplate.defaultIsActive),
      settings: this._fb.array([]),
    });
    this.templateForm.get('portalType').disable();
    if (pluginTemplate.settings) {
      for (let attrKey of Object.keys(pluginTemplate.settings)) {
        (this.templateForm.get("settings") as FormArray).push(this._fb.group({
          key: this._fb.control(attrKey, Validators.required),
          name: this._fb.control(pluginTemplate.settings[attrKey].name, Validators.required),
          type: this._fb.control(pluginTemplate.settings[attrKey].type, Validators.required),
          value: this._fb.control(pluginTemplate.settings[attrKey].value)
        }));
      }
    }
    this.modalOpen("Edit Template", "Save Changes");
  }

  public newPlugin() {
    this.selectedTemplate = null;
    if (this.templateForm) {
      this.templateForm.get('portalType').enable();
    }
    this.templateForm = this._fb.group({
      _id: this._fb.control(null),
      name: this._fb.control(''),
      code: this._fb.control('', Validators.required),
      plan: this._fb.control('starter', Validators.required),
      description: this._fb.control(''),
      page: this._fb.control(this.page?this.getPageById(this.page):'', Validators.required),
      portalType: this._fb.control('community', Validators.required),
      placement: this._fb.control('top', Validators.required),
      order: this._fb.control(''),
      portalSpecific: this._fb.control(''),
      defaultIsActive: this._fb.control(false),
      settings: this._fb.array([]),
      object: this._fb.control({})
    });
    // this.addNewAttr();
    this.modalOpen("Create template", "Create");
  }

  private modalOpen(title: string, yesBtn: string) {
    this.editModal.okButtonLeft = false;
    this.editModal.alertTitle = title;
    this.editModal.okButtonText = yesBtn;
    this.editModal.open();
  }

  public swap(templateToMoveUp, templateToMoveDown, placement) {

    this.move(this.templatesByPlacement.get(placement)[templateToMoveUp], true);
    this.move(this.templatesByPlacement.get(placement)[templateToMoveDown], false);

  }

  public move(template: PluginTemplate, up: boolean) {
    this.showLoading = true;
    this.subscriptions.push(this._pluginsService.updatePluginTemplateOrder(template, this.properties.adminToolsAPIURL, up ? -1 : 1).subscribe(
      saved => {
        this.savedSuccessfully(saved, true);

        // this._clearCacheService.clearCache("Template updates");
      },
      error => this.handleUpdateError("System error creating template", error)
    ));
  }

  public saveConfirmed(data: any) {
    this.showLoading = true;
    let template: PluginTemplate = <PluginTemplate>this.templateForm.getRawValue();
    template.page = this.templateForm.getRawValue().page._id
    template.portalSpecific = this.templateForm.getRawValue().portalSpecific.length > 0? this.templateForm.getRawValue().portalSpecific.split(','):[];
    template.object = this.selectedTemplate?this.selectedTemplate.object:PluginUtils.initializeObjectAndCompare(template.code);
    template.settings = new Map<string, { name: string; type: string; value: string }>();
    this.editSubmenuOpen = false;
    if(!template._id){
      template.order = this.templatesByPlacement.get(template.placement).length > 0 ? this.templatesByPlacement.get(template.placement).length:0;
    }
    for (let attr of this.templateForm.getRawValue().settings) {
      template.settings[attr.key] = {name: attr.name, type: attr.type, value: attr.value};
    }
    let update = template._id ? true : false;
    this.subscriptions.push(this._pluginsService.savePluginTemplate(template, this.properties.adminToolsAPIURL).subscribe(
      saved => {
        this.selectedTemplate = saved;
        this.savedSuccessfully(saved, update);
        NotificationHandler.rise('Template <b>' + saved.name + '</b> has been <b>successfully' + (update ? ' updated ' : ' created ') + '</b>');
        // this._clearCacheService.clearCache("Template id saved");
      },
      error => this.handleUpdateError("System error creating template", error)
    ));
  }

  public savedSuccessfully(template: PluginTemplate, update: boolean) {
    if (update) {
      let index =  this.templatesByPlacement.get(this.selectedTemplate.placement).findIndex(value => value._id === template._id);
      this.templatesByPlacement.get(this.selectedTemplate.placement)[index] = template;
      // TODO sort
      // this.templatesByPlacement.get(this.selectedTemplate.placement) = this.templatesByPlacement.get(this.selectedTemplate.placement).sort()
    } else {
      template.object = PluginUtils.initializeObjectAndCompare(template.code, template.object)
      this.templatesByPlacement.get(this.selectedTemplate.placement).push(template);
    }

    this.showLoading = false;
  }

  public filter(plugin: PluginTemplate): boolean {
    return this.searchText.toString() == '' || (plugin.name + ' ' + plugin.portalType).match(this.searchText) != null;
  }

  handleUpdateError(message: string, error = null) {
    if (error) {
      console.log('Server responded: ' + error);
    }
    NotificationHandler.rise(message, 'danger');
    this.showLoading = false;
  }

  handleError(message: string, error = null) {
    if (error) {
      console.log('Server responded: ' + error);
    }
    NotificationHandler.rise(message, 'danger');
    this.showLoading = false;
  }

  getPages() {
    this.showLoading = true;
    this.subscriptions.push(this._helpContentService.getAllPages(this.properties.adminToolsAPIURL).subscribe(
      pages => {
        this.allPages = [];
        this.allPagesByPortal = new Map();
        pages.forEach(page => {
          let option = {
            label: page.name + " [" + page.portalType + "]",
            value: page
          };
          this.allPages.push(option);
          if (!this.allPagesByPortal.has(page.portalType)) {
            this.allPagesByPortal.set(page.portalType, [])
          }
          this.allPagesByPortal.get(page.portalType).push(option)
        });
        this.showLoading = false;
      },
      error => this.handleError('System error retrieving pages', error)
    ));
  }

  addNewAttr() {
    (this.templateForm.get("settings") as FormArray).push(this._fb.group({
      key: this._fb.control("", Validators.required),
      name: this._fb.control("", Validators.required),
      type: this._fb.control("text", Validators.required),
      value: this._fb.control("")
    }));
  }

  removeAttr(index) {
    this.attrFormArray.removeAt(index);
    this.attrFormArray.markAsDirty();
  }

  get attrFormArray() {

    return this.templateForm.get("settings") as FormArray;

  }

  attributeTypeChanged(form) {
    let type = form.get("value").get("type");
    form.get("value").setValue("");
    if (type == "boolean") {
      form.get("value").setValue(false);
    }
  }

  public getPageAsString(pageId): string {
    return this.allPages.filter(option => option.value._id == pageId).map((option => option.value.name + " [" + option.value.portalType + "]")).join(",");
  }

  public getPageById(pageId) {
    for (let option of this.allPages) {
      if (option.value._id == pageId) {
        return option.value;
      }
    }
    return pageId;
  }


  pluginFieldChanged($event:PluginEditEvent){
    if($event.type == "open-submenu"){
      this.editSubmenuOpen = true;
      return;
    }
    if($event.type == "close-submenu"){

      this.editSubmenuOpen = false;
      return;
    }
    this.selectedTemplate.object[$event.field]=$event.value;
    this.templateForm.markAsDirty();
  }
  public getPagesByPortal(portal) {
    return this.allPages.filter(option => option.value.portalType == portal);
  }
}
