import { Component, OnInit, Inject } from '@angular/core';
import { MatDialogRef, MatSnackBar } from '@angular/material';
import { DarsApiService } from '../services/api.service';
import { DegreeProgram } from '../models/degree-program';
import { StudentDegreeProgram } from '../models/student-degree-program';
import { Observable } from 'rxjs';
import { Store, select } from '@ngrx/store';
import { GlobalState } from '@app/core/state';
import * as selectors from '../store/selectors';
import { DARSState } from '../store/state';
import { MAT_DIALOG_DATA } from '@angular/material';
import {
  FormBuilder,
  FormGroup,
  FormControl,
  Validators,
  FormArray,
  AbstractControl,
} from '@angular/forms';

@Component({
  selector: 'cse-new-audit-options',
  templateUrl: './new-audit-options.component.html',
  styleUrls: ['./new-audit-options.component.scss'],
})
export class NewAuditOptionsComponent implements OnInit {
  public newAuditForm: FormGroup;
  public degreeProgram: DegreeProgram;
  public degreePrograms: any;
  public programOfStudy: string;
  public studentDegreeProgram: StudentDegreeProgram[];
  public DARSprograms: any;
  public honorsOptions: any;
  public courses: any;
  public variableCreditCourses: any;
  public degreePlans$: Observable<DARSState['degreePlans']>;
  public degreePlans: any[];
  public primaryPlan: any[];
  public primaryPlanId: string;
  public hasVariableCredits: boolean;
  public creditsRange: any[];
  public isLoaded: boolean;
  public selectedAuditType: string;
  public termsToInclude: any[];
  get formArray(): AbstractControl | null {
    return this.newAuditForm.get('formArray');
  }

  constructor(
    private fb: FormBuilder,
    private dialogRef: MatDialogRef<NewAuditOptionsComponent>,
    private snackBar: MatSnackBar,
    private api: DarsApiService,
    private store: Store<GlobalState>,
    @Inject(MAT_DIALOG_DATA)
    data: {
      selectedAuditType: string;
    },
  ) {
    this.selectedAuditType = data.selectedAuditType;
    this.termsToInclude = [
      {
        name: 'Previous, current, future, and planned terms',
        id: 'future-whatif',
        value: 'future',
      },
      {
        name: 'Previous, current, future',
        id: 'future-degree',
        value: 'future',
      },
      { name: 'Previous, current', id: 'current', value: 'current' },
      { name: 'Previous', id: 'previous', value: 'previous' },
    ];
  }

  ngOnInit() {
    // Get Degree plans
    this.degreePlans$ = this.store.pipe(select(selectors.degreePlans));
    this.degreePlans$.subscribe(plans => {
      this.degreePlans = plans;
      this.primaryPlan = plans.filter(function(plan) {
        return plan.primary === true;
      });
      this.primaryPlanId = this.primaryPlan[0].roadmapId.toString();
    });
    // Get student degree programs
    this.api.getStudentDegreePrograms().subscribe(studentDegreeProgram => {
      this.studentDegreeProgram = studentDegreeProgram;
    });

    this.api.getStaticData().subscribe(degreePrograms => {
      this.degreePrograms = degreePrograms;
      this.honorsOptions = [];
      this.DARSprograms = [];
      for (var school in this.degreePrograms) {
        // Get program of study
        this.programOfStudy = this.degreePrograms[
          school
        ].darsInstitutionCodeDescription;
        // Get honors options
        if (this.degreePrograms[school].hasOwnProperty('honorsOptions')) {
          this.honorsOptions.push(...this.degreePrograms[school].honorsOptions);
        }
        // Get DARS programs
        if (this.degreePrograms[school].hasOwnProperty('programs')) {
          this.DARSprograms.push(...this.degreePrograms[school].programs);
        }
      }
    });
    this.newAuditForm = this.fb.group({
      formArray: this.fb.array([
        this.fb.group({
          auditType: new FormControl(''),
        }),
        this.fb.group({
          darsDegreeProgram: new FormControl(''),
          darsInstitution: new FormControl(''),
          darsInstitutionProgram: new FormControl(''),
        }),
        this.fb.group({
          honors: new FormControl('Keep current status'),
          includeCoursesFrom: new FormControl(
            this.selectedAuditType === 'degree'
              ? this.termsToInclude[1]
              : this.termsToInclude[0],
          ),
          runAgainst: new FormControl(this.primaryPlanId),
        }),
        this.fb.group({
          credits: new FormControl(''),
        }),
      ]),
    });
  }

  public getCoursesList(roadmapId) {
    this.isLoaded = false;

    this.api.getAllCourses(roadmapId).subscribe(courses => {
      this.courses = courses;
      this.creditsRange = [];
      this.courses ? (this.isLoaded = true) : (this.isLoaded = false);
      this.courses.forEach(function(course) {
        course.creditMin === course.creditMax
          ? (this.hasVariableCredits = false)
          : (this.hasVariableCredits = true);

        // Build creditsRange array
        course.creditsRange = [];
        for (let i = course.creditMin; i <= course.creditMax; i++) {
          course.creditsRange.push(i);
        }
      }, this);
    });
  }

  public runDARSAudit() {
    const {
      auditType,
      programOfStudy,
      academicProgram,
      honors,
      includeCoursesFrom,
      runAgainst,
      credits,
    } = this.newAuditForm.value;

    this.dialogRef.close();
    this.snackBar.open(
      'Audit in progress. You will be notified when the audit is ready to be viewed.',
    );
  }
}