{"size": 1683, "ext": "js", "max_stars_repo_path": "source/iml/resettable-group/resettable-group.js", "max_stars_repo_name": "intel-hpdd/GUI", "max_stars_repo_stars_event_min_datetime": "2017-05-16T16:10:13.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-13T15:57:18.000Z", "max_issues_repo_path": "source/iml/resettable-group/resettable-group.js", "max_issues_repo_name": "intel-hpdd/GUI", "max_issues_repo_issues_event_min_datetime": "2017-05-12T21:11:34.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-16T21:19:37.000Z", "max_forks_repo_path": "source/iml/resettable-group/resettable-group.js", "max_forks_repo_name": "intel-hpdd/GUI", "max_forks_repo_forks_event_min_datetime": "2017-06-16T15:57:59.000Z", "max_forks_repo_forks_event_max_datetime": "2017-06-16T15:57:59.000Z"}
{"max_stars_count": 2, "max_issues_count": 110, "max_forks_count": 1, "avg_line_length": 20.5243902439, "max_line_length": 64, "alphanum_fraction": 0.5947712418}
// @flow

//
// Copyright (c) 2018 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

import * as fp from "@iml/fp";

type ctrl = {
  $name: string,
  $addControl: Function,
  $formatters: Array<(val: any) => any>,
  $setViewValue: (val: any, evt?: string) => void,
  $setPristine: () => void,
  $setUntouched: () => void,
  $render: () => void
};

type itm = {
  initialValue: any,
  item: ctrl
};

export class ResettableGroupController {
  controls: Array<itm> = [];
  formCtrl: ctrl;
  localApply: Function;

  constructor($scope: Object, localApply: Function) {
    "ngInject";
    this.localApply = localApply.bind(null, $scope);
  }

  $onInit() {
    const addControl = (control: ctrl): ctrl => {
      if (control.$name === "") return control;

      if (control.$addControl) {
        control.$addControl = fp.flow(
          addControl,
          fp.bindMethod("$addControl")(control)
        );

        return control;
      }

      const item = { initialValue: undefined, item: control };
      this.controls.push(item);
      const setOnce = fp.once(val => (item.initialValue = val));

      control.$formatters.push(x => {
        setOnce(x);
        return x;
      });

      return control;
    };

    addControl(this.formCtrl);
  }

  reset() {
    this.controls.forEach(entry => {
      entry.item.$setViewValue(entry.initialValue);
      entry.item.$setPristine();
      entry.item.$setUntouched();
      entry.item.$render();
    });

    this.localApply();
  }
}

export default {
  scope: {},
  require: {
    formCtrl: "^form"
  },
  controller: ResettableGroupController
};
