import { Component } from '@angular/core';
import { HomePage } from './home.page';

@Component({
  template: `<ion-nav [root]="rootPage"></ion-nav>`
})
export class AppComponent {

  rootPage = HomePage;

}


/*
Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
*/
import { NgModule, ErrorHandler } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { FlexLayoutModule } from "@angular/flex-layout";
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { HomePage } from './home.page';
import { Service } from './service';
import { HttpModule  } from '@angular/http';


@NgModule({
  imports: [ IonicModule.forRoot(AppComponent),
  BrowserModule, FormsModule, HttpModule , ReactiveFormsModule],
  declarations: [ AppComponent, HomePage ],
  entryComponents: [ HomePage ],
  providers: [
    {provide: ErrorHandler, useClass: IonicErrorHandler},
    Service
    ],
  bootstrap: [ IonicApp ]
})
export class AppModule { }


/*
Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
*/
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app.module';

const platform = platformBrowserDynamic();
platform.bootstrapModule(AppModule);


/*
Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
*/
import { Component, ViewChild, NgForm } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Service } from './service';
import { FormBuilder, FormGroup, Validators, FormControl, FormArray } from '@angular/forms';
import { Http, Headers } from '@angular/http';

@Component({
  selector: 'page-home',
  templateUrl: 'app/home.page.html'
})
export class HomePage {
  
  cat: number = 1;
  
  questions = [{id:1,text:'Question 1', answers:[{id:1},{id:2}]},{id:2,text:'Question 2', answers:[{id:11},{id:22}]}]
  
  list_services = [{id: 1, desc: 's1'},
                   {id: 2, desc: 's2'}];
                   
  staffs = [{id: 1, staff: 'st1' }, 
            {id: 2, staff: 'st2' }]                   

  my_arr = [1,2];
  
  formServicesArr = new FormArray([]);              
  
  
  validation_messages = {
    'username': [
    		{ type: 'required', message: 'Username is required.' },
    		{ type: 'minlength', message: 'Username must be at least 5 characters long.' },
    		{ type: 'maxlength', message: 'Username cannot be more than 25 characters long.' },
    		{ type: 'pattern', message: 'Your username must contain only numbers and letters.' },
    		{ type: 'validUsername', message: 'Your username has already been taken.' }
    	],
	  'name': [
		  { type: 'required', message: 'Name is required.' }
	  ],
	  'email': [
    		{ type: 'required', message: 'Email is required.' },
    		{ type: 'pattern', message: 'Invalid email.' },
    	],

  }
  
  apiUrl = '';
  test_token: any;
  
  constructor(private navController: NavController, private service: Service, private formBuilder:FormBuilder, private http: Http) { 
   

    let group = [];
    
    this.list_services.forEach((l) => {
      group.push(new FormGroup({
        key: new FormControl(l.id),
        value: new FormControl(l.desc),
        checked: new FormControl(false),
      }))
    });
    
    this.formServicesArr = new FormArray(group);
    
    this.formServicesArr.valueChanges.subscribe((v) => {
      this.surveyForm.controls.selected_services.setValue(this.mapItems(v));
    });
    
    
    this.surveyForm = this.formBuilder.group({
      name: new FormControl('', Validators.required),
      email: new FormControl('', Validators.compose([
			 Validators.required,
			 Validators.pattern('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$')
		 ])),
      services: this.formBuilder.array([]),
      selected_services: new FormControl(this.mapItems(this.formServicesArr.value), Validators.required),
      request_staf_id: new FormControl('-1'),
      has_appt: new FormControl('false'),
    })
    
    
    this.surveyForm.setControl('services', this.formServicesArr);
    
    // this.getUsers().then(data => {
    //   this.test_token = data;
    //   console.log(this.test_token);
    // });
  }

  mapItems(items) {
      let selectedItems = items.filter((l) => l.checked).map((l) => l.key);
      return selectedItems.length ? selectedItems : null;
    }
    
  
  onChange(id, isChecked, index) {
    const answers = <FormArray>this.surveyForm.controls.questions.controls[index].controls.answer_ids
    
    if(isChecked) {
      answers.push(new FormControl(id))
    } else {
      let idx = answers.controls.findIndex(x => x.value == id)
      answers.removeAt(idx)
    }
  }
  
  onChangeService(id, isChecked) {
    console.log(id);
    console.log(isChecked);
    //const selected_services = <FormArray>this.surveyForm.controls.selected_services.controls[index].controls.answer_ids;
    if(isChecked) {
      this.surveyForm.controls['services'].push(new FormControl(id))
    } else {
      //let idx = this.selected_services.controls.findIndex(x => x.value == id);
      //this.selected_services.removeAt(idx);
    }
  }
  
  
  getUsers() {
    let headers = new Headers();
    headers.append('apikey', '84A40E24-4D63-CD06-E050-007F01005955');
    headers.append('content-type', 'application/json');
   
    return new Promise(resolve => {
      this.http.post(this.apiUrl , {
        headers: headers
    }).subscribe(data => {
        resolve(data);
      }, err => {
        console.log(err);
      });
    });
  }

  refreshCat(cat){
    this.cat = cat;
  }
}
<ion-header>
  <ion-navbar>
    <ion-title>{{ appName }}</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <!-- <ion-segment>
    <ion-segment-button value="1" (click)="refreshCat(1)">
        1
    </ion-segment-button>
    <ion-segment-button value="2" (click)="refreshCat(2)">
        2
    </ion-segment-button>
  </ion-segment> -->

  <div *ngIf="surveyForm">
    <form [formGroup]="surveyForm">
      <!--<div formArrayName="questions">-->
      <!--  <div *ngFor="let question of questions; let i = index" [formGroupName]="i" padding-bottom>-->
      <!--    <ion-row>-->
      <!--      <ion-col col-10>-->
      <!--        <h5>{{ question.text }}</h5>-->
      <!--        <ng-container>-->
      <!--          <ion-list formArrayName="answer_ids">-->
      <!--            <div >-->
      <!--              <ion-item *ngFor="let choice of question.answers; let j = index">-->
      <!--                <ion-label style="white-space: normal;">{{ choice.id }}</ion-label>-->
      <!--                <ion-checkbox (ionChange)="onChange(choice.id, $event.checked, i)" value="choice.id"></ion-checkbox>-->
      <!--              </ion-item>-->
      <!--            </div>-->
      <!--          </ion-list>-->
      <!--        </ng-container>-->
      <!--      </ion-col>-->
      <!--    </ion-row>-->
      <!--</div>-->
      <!-- </div>-->
     
      <div formArrayName="services">
        
        <ion-list>
          
        <div *ngFor="let ser of surveyForm.controls.services.controls; let i = index;" [formGroup]="ser">
          <ion-item-sliding #item *ngIf="ser.id==cat">
           <ion-item>
              <ion-label>{{ ser.value.value | json }}</ion-label>
              <ion-checkbox formControlName="checked" ></ion-checkbox>
            </ion-item>
     
            <ion-item-options side="right">
              <button ion-button (click)="unread(item)">Unread</button>
            </ion-item-options>
                     </ion-item-sliding>
        </div>

         </ion-list>
         
      </div>
     
  
  
      <ion-item>
        <ion-label stacked>Name: </ion-label>
        <ion-input type="password" formControlName="name" name="name" clearInput clearOnEdit="true"></ion-input>
      </ion-item>
      <div class="validation-errors">
      	<ng-container *ngFor="let validation of validation_messages.name" >
      		<div class="error-message" *ngIf="surveyForm.get('name').hasError(validation.type) && (surveyForm.get('name').dirty || surveyForm.get('name').touched)">
      			<ion-item><ion-label stacked>{{ validation.message }}</ion-label></ion-item>
      		</div>
      	</ng-container>
      </div>
      
      <ion-item>
        <ion-label stacked>Email: </ion-label>
        <ion-input type="text" formControlName="email" name="email"></ion-input>
      </ion-item>
      <div class="validation-errors">
      	<ng-container *ngFor="let validation of validation_messages.email" >
      		<div class="error-message" *ngIf="surveyForm.get('email').hasError(validation.type) && (surveyForm.get('email').dirty || surveyForm.get('email').touched)">
      			<ion-item><ion-label stacked>{{ validation.message }}</ion-label></ion-item>
      		</div>
      	</ng-container>
      </div>
      

      <ion-item no-lines>
    <ion-label class="label_c1">Request Staff</ion-label>
   
    <ion-select formControlName="request_staf_id"  name="request_staf_id">
      <ion-option value="-1">None</ion-option>
      <ion-option *ngFor="let staff of staffs" value="{{staff.id}}">{{staff.staff}}
      </ion-option >  
    </ion-select>                            
  </ion-item>

  <ion-item no-lines>
    <ion-label class="label_c1">Do?</ion-label>
    <ion-toggle formControlName="has_appt" name="flg_has_appt" toggle-class="toggle-calm"></ion-toggle>
  </ion-item>
  
  
  
    </form>
  </div>
  
  <pre>{{ test_token }}</pre>
  
  
  <pre>{{surveyForm.value  | json }}</pre>

  <pre>{{surveyForm.valid }}</pre>
</ion-content>
[{
    "PageRec":"AL005",
    "State":"AL",
    "County":"Autauga County",
    "CityTown":null,
    "Zip":null,
    "ShowRecordingInfo":"true",
    "Deed":{
        "Checked":"True",
        "Pages":"1",
        "ConsiderationAmount":"150000"
        },
    "MortgageDeed":{
        "Checked":"False",
        "Pages":null,
        "NewDebtAmount":null
        },
    "MortgageRefi":{
        "Checked":"False",
        "Pages":null,
        "NewDebtAmount":null,
        "OriginalDebt":null,
        "UnpaidDebt":null
        },
    "Assignment":{
        "Checked":"False",
        "Pages":null,
        "Assignments":null
        },
    "ReleaseSatisfaction":{
        "Checked":"False",
        "Pages":null,
        "ReleasesSatisfactions":null
        },
    "Questions":{
        "Question":{
            "Number":"Q4",
            "Category":"Deed",
            "Type":"bool",
            "Question Text":"Are the deed and ``mortgage being recorded at the same time?",
            "Answer":"1"
            }
        }
}]
import {Injectable} from '@angular/core';
import {Http} from '@angular/http';
import 'rxjs/Rx';

@Injectable()
export class Service{

constructor(private http:Http){

}

getData(){
    return this.http.get('app/data.json').map(res => res.json());
}
}
<!DOCTYPE html>
<html>
  <head>
    <title>Ionic 2 QuickStart</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- 1. Load libraries -->
     <!-- Polyfill(s) for older browsers -->
    <script src="https://unpkg.com/core-js@2.4.1/client/shim.min.js"></script>

    <script src="https://unpkg.com/zone.js@0.6.26?main=browser"></script>
    <script src="https://unpkg.com/systemjs@0.19.40/dist/system.src.js"></script>

    <!-- 2. Configure SystemJS -->
    <script src="systemjs.config.js"></script>
    <link href="https://unpkg.com/ionic-angular@3.2.1/css/ionic.css" rel="stylesheet">
  </head>

  <!-- 3. Display the application -->
  <body>
    <ion-app></ion-app>
    <script>
      System.import('app').catch(function(err){ console.error(err); });
    </script>
  </body>
</html>


<!-- 
Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
-->
### Ionic 2 Plunk

Basic Ionic 2 plunk based on the Angular QuickStart plunk.
/**
 * PLUNKER VERSION
 * (based on systemjs.config.js in angular.io)
 * System configuration for Angular samples
 * Adjust as necessary for your application needs.
 */
(function (global) {
  System.config({
    // DEMO ONLY! REAL CODE SHOULD NOT TRANSPILE IN THE BROWSER
    transpiler: 'ts',
    typescriptOptions: {
      tsconfig: true
    },
    meta: {
      'typescript': {
        "exports": "ts"
      }
    },
    paths: {
      // paths serve as alias
      'npm:': 'https://unpkg.com/'
    },
    // map tells the System loader where to look for things
    map: {
      // our app is within the app folder
      app: 'app',

      // angular bundles
      // angular bundles
      '@angular/core': 'npm:@angular/core@4.2.2/bundles/core.umd.js',
      '@angular/common': 'npm:@angular/common@4.2.2/bundles/common.umd.js',
      '@angular/compiler': 'npm:@angular/compiler@4.2.2/bundles/compiler.umd.js',
      '@angular/platform-browser': 'npm:@angular/platform-browser@4.2.2/bundles/platform-browser.umd.js',
      '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic@4.2.2/bundles/platform-browser-dynamic.umd.js',
      '@angular/http': 'npm:@angular/http@4.2.2/bundles/http.umd.js',
      '@angular/forms': 'npm:@angular/forms@4.2.2/bundles/forms.umd.js',
  
      'ionic-angular': 'npm:ionic-angular@3.4.0',
      'rxjs': 'npm:rxjs@5.4.1',
      'ts': 'npm:plugin-typescript@5.2.7/lib/plugin.js',
      'typescript': 'npm:typescript@2.2.1/lib/typescript.js',

    },
    // packages tells the System loader how to load when no filename and/or no extension
    packages: {
      app: {
        main: './main.ts',
        defaultExtension: 'ts'
      },
      rxjs: {
        defaultExtension: 'js'
      },
      'ionic-angular': {
        main: './umd/index.js',
        defaultExtension: 'js'
      }
    }
  });
})(this);


/*
Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
*/
{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true
  }
}