import {ChangeDetectorRef, Component, OnInit, ViewChild} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {UntypedFormBuilder, UntypedFormGroup, Validators} from '@angular/forms';
import {Page} from '../../utils/entities/adminTool/page';
import {HelpContentService} from '../../services/help-content.service';
import {EnvProperties} from '../../utils/properties/env-properties';
import {properties} from '../../../../environments/environment';
import {Subscriber, Subscription, zip} from 'rxjs';
import {DivHelpContent} from '../../utils/entities/adminTool/div-help-content';
import {NotificationHandler} from "../../utils/notification-handler";
import {ClearCacheService} from "../../services/clear-cache.service";
import {CKEditorComponent} from "ng2-ckeditor";

@Component({
  selector: 'class-content-form',
  templateUrl: './class-help-content-form.component.html',
})
export class ClassContentFormComponent implements OnInit {

  myForm: UntypedFormGroup;
  portal: string;
  parentClass: string;
  pageId: string;
  pageContentId: string;
  page: Page;
  classOptions = [];
  public properties: EnvProperties = properties;
  public showLoading: boolean = true;
  private subs: Subscription[] = [];
  public pageHelpContent: DivHelpContent;
  @ViewChild('ckEditor') ckEditor: CKEditorComponent;

  constructor(private route: ActivatedRoute, private _router: Router, private _fb: UntypedFormBuilder,
              private cdr: ChangeDetectorRef, private _helpContentService: HelpContentService,
              private _clearCacheService: ClearCacheService) {
  }

  ngOnInit() {
    this.portal = (this.route.snapshot.data.portal) ? this.route.snapshot.data.portal : this.route.snapshot.params[this.route.snapshot.data.param];
    this.parentClass = this.route.snapshot.data.parentClass;
    this.subs.push(this.route.queryParams.subscribe(params => {
      this.pageId = params['pageId'];
      this.myForm = this.form;
      this.pageContentId = params['pageContentId'];
      if (!this.pageId) {
        this._router.navigate(['../'], {relativeTo: this.route});
      }
      this.getInfo(this.pageId);
    }));
  }

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

  getInfo(pageId: string) {
    this.showLoading = true;
    let obs = zip(this._helpContentService.getPageByPortal(pageId, this.properties.adminToolsAPIURL, this.portal),
      this._helpContentService.getDivIdsFullByPortal(pageId, this.properties.adminToolsAPIURL, this.portal));
    this.subs.push(obs.subscribe(
      results => {
        this.page = results[0];
        if (this.properties.adminToolsPortalType != this.page.portalType) {
          this._router.navigate(['../'], {relativeTo: this.route});
        }
        this.setOptions(results[1]);
        if (!this.pageContentId) {
          this.updateForm(null);
          this.showLoading = false;
          this.initCKEditor();
        } else {
          this.subs.push(this._helpContentService.getDivHelpContent(this.pageContentId, this.properties.adminToolsAPIURL, this.portal).subscribe(pageHelpContent => {
              this.pageHelpContent = pageHelpContent;
              if (this.properties.adminToolsPortalType != this.page.portalType) {
                this._router.navigate(['../'], {relativeTo: this.route});
              }
              this.updateForm(this.pageHelpContent);
              this.showLoading = false;
              this.initCKEditor();
            },
            error => {
              this.handleError('System error retrieving content by id ' + this.pageContentId, error)
            }));
        }
      }));

  }

  private initCKEditor() {
    this.cdr.detectChanges();
    if (this.ckEditor) {
      this.ckEditor.instance.on('mode', () => {
        let editor = this.ckEditor.instance;
        if (editor.mode === 'source') {
          let editable = editor.editable();
          editable.attachListener(editable, 'input', () => {
            this.myForm.get('content').setValue(editor.getData());
            this.myForm.get('content').markAsDirty();
            this.cdr.detectChanges();
          });
        }
      });
    }
  }

  private updateForm(pageHelpContent: DivHelpContent) {
    this.pageHelpContent = pageHelpContent;
    this.myForm = this.form;
    if (this.pageHelpContent) {
      this.myForm.patchValue((pageHelpContent));
      this.myForm.get('divId').disable();
    }
    this.myForm.markAsPristine();

  }


  public setOptions(divIds) {
    this.classOptions = [];
    for (let divid of divIds) {
      this.classOptions.push({label: divid.name, value: divid._id});
    }

  }

  public get form() {
    return this._fb.group({
      divId: ['', Validators.required],
      content: ['', Validators.required],
      isActive: true,
      portal: this.portal,
      _id: '',
    });

  }

  public reset() {
    this.myForm.patchValue({
      divId: ['', Validators.required],
      content: ['', Validators.required],
      isActive: true,
      portal: '',
      _id: '',
    });
    this.myForm.markAsPristine();
  }

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

  public saveCustom() {
    if (this.myForm.valid) {
      this.showLoading = true;
      let pageHelpContent: DivHelpContent = this.myForm.getRawValue();
      this.subs.push(this._helpContentService.insertOrUpdateDivHelpContent(pageHelpContent, this.properties.adminToolsAPIURL, this.portal).subscribe(
        _ => {
          this._router.navigate(['../'], {queryParams: {"pageId": this.pageId}, relativeTo: this.route});
          NotificationHandler.rise('Page content has been <b>successfully updated</b>');
          this.showLoading = false;
          this._clearCacheService.clearCacheInRoute("Class help text saved or updated",this.portal, this.page.route);
        },
        err => this.handleUpdateError('System error saving page content', err)
      ));
    } else {
      this.showLoading = false;
      this.handleError('Please fill all required fields');
    }
  }

  public resetCustom() {
    this.showLoading = true;
    this.updateForm(this.pageHelpContent);
    this.showLoading = false;
  }

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

  changeStatus() {
    this.myForm.get('isActive').setValue(!this.myForm.get('isActive').value);
    if (this.pageHelpContent && this.myForm.get('isActive').value != this.pageHelpContent.isActive || !this.pageHelpContent && !this.myForm.get('isActive').value) {
      this.myForm.get('isActive').markAsDirty();
    } else {
      this.myForm.get('isActive').markAsPristine()
    }
  }

  contentChanged() {
    if (this.pageHelpContent && this.myForm.get('content').value != this.pageHelpContent.content || !this.pageHelpContent && this.myForm.get('content').value != '') {
      this.myForm.get('content').markAsDirty();
    } else {
      this.myForm.get('content').markAsPristine()
    }
  }
}
