import { Component, OnInit } from '@angular/core';
import {Router} from '@angular/router';
import {DataService} from '../services/data.service';
import {ApiService} from '../services/api.service';
import {HelpModel} from '../models/help.model';
import {LoginService} from '../services/login.service';

@Component({
  selector: 'app-help',
  templateUrl: './help.component.html',
  styleUrls: ['./help.component.scss']
})
export class HelpComponent implements OnInit {

  content: HelpModel = new HelpModel().deserialize({text: null, level: 'none'});  // help content
  edit = false;        // set true to change to edit mode
  private route = '';  // URIComponent encoded route which serves as a key to fetch the help document

  constructor(
    private router: Router,
    public d: DataService,
    private api: ApiService,
    public login: LoginService
  ) { }

  ngOnInit(): void {
    // remove ids from path
    this.route = encodeURIComponent(this.router.url.replace(/\/[0-9a-f]{24}/, ''));
    this.api.get<HelpModel>('/help/' + this.route, (data, err) => {
      if (!err) {  // content was found
        this.content = new HelpModel().deserialize(data);
      }
      else {
        this.content.text = '';
      }
    });
  }

  saveHelp() {
    this.api.post('/help/' + this.route, this.content.sendFormat(), () => {
      this.edit = false;
    });
  }

  deleteHelp() {
    this.api.delete('/help/' + this.route, (ignore, err) => {
      if (!err) {
        this.content = new HelpModel().deserialize({text: null, level: 'none'});
        this.edit = false;
      }
    });
  }
}
