40f649cff6ef2367163c2732c567e2c817b090e1
[oweals/peertube.git] / client / src / app / +admin / users / user-edit / user-add.component.ts
1 import { Component, OnInit } from '@angular/core'
2 import { FormBuilder, FormGroup } from '@angular/forms'
3 import { Router } from '@angular/router'
4
5 import { NotificationsService } from 'angular2-notifications'
6
7 import { UserService } from '../shared'
8 import {
9   USER_USERNAME,
10   USER_EMAIL,
11   USER_PASSWORD,
12   USER_VIDEO_QUOTA
13 } from '../../../shared'
14 import { UserCreate } from '../../../../../../shared'
15 import { UserEdit } from './user-edit'
16
17 @Component({
18   selector: 'my-user-add',
19   templateUrl: './user-edit.component.html'
20 })
21 export class UserAddComponent extends UserEdit implements OnInit {
22   error: string
23
24   form: FormGroup
25   formErrors = {
26     'username': '',
27     'email': '',
28     'password': '',
29     'videoQuota': ''
30   }
31   validationMessages = {
32     'username': USER_USERNAME.MESSAGES,
33     'email': USER_EMAIL.MESSAGES,
34     'password': USER_PASSWORD.MESSAGES,
35     'videoQuota': USER_VIDEO_QUOTA.MESSAGES
36   }
37
38   constructor (
39     private formBuilder: FormBuilder,
40     private router: Router,
41     private notificationsService: NotificationsService,
42     private userService: UserService
43   ) {
44     super()
45   }
46
47   buildForm () {
48     this.form = this.formBuilder.group({
49       username: [ '', USER_USERNAME.VALIDATORS ],
50       email:    [ '', USER_EMAIL.VALIDATORS ],
51       password: [ '', USER_PASSWORD.VALIDATORS ],
52       videoQuota: [ '-1', USER_VIDEO_QUOTA.VALIDATORS ]
53     })
54
55     this.form.valueChanges.subscribe(data => this.onValueChanged(data))
56   }
57
58   ngOnInit () {
59     this.buildForm()
60   }
61
62   formValidated () {
63     this.error = undefined
64
65     const userCreate: UserCreate = this.form.value
66
67     // A select in HTML is always mapped as a string, we convert it to number
68     userCreate.videoQuota = parseInt(this.form.value['videoQuota'], 10)
69
70     this.userService.addUser(userCreate).subscribe(
71       () => {
72         this.notificationsService.success('Success', `User ${userCreate.username} created.`)
73         this.router.navigate([ '/admin/users/list' ])
74       },
75
76       err => this.error = err.text
77     )
78   }
79
80   isCreation () {
81     return true
82   }
83
84   getFormButtonTitle () {
85     return 'Add user'
86   }
87 }