Create wt-odlux directory
[ccsdk/features.git] / sdnr / wt-odlux / odlux / apps / mediatorApp / src / components / editMediatorServerDialog.tsx
1 /**
2  * ============LICENSE_START========================================================================
3  * ONAP : ccsdk feature sdnr wt odlux
4  * =================================================================================================
5  * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved.
6  * =================================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
8  * in compliance with the License. You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software distributed under the License
13  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
14  * or implied. See the License for the specific language governing permissions and limitations under
15  * the License.
16  * ============LICENSE_END==========================================================================
17  */
18 import * as React from 'react';
19
20 import Button from '@mui/material/Button';
21 import TextField from '@mui/material/TextField';
22 import Dialog from '@mui/material/Dialog';
23 import DialogActions from '@mui/material/DialogActions';
24 import DialogContent from '@mui/material/DialogContent';
25 import DialogContentText from '@mui/material/DialogContentText';
26 import DialogTitle from '@mui/material/DialogTitle';
27
28 import { IDispatcher, connect, Connect } from '../../../../framework/src/flux/connect';
29
30 import { addAvaliableMediatorServerAsyncActionCreator, removeAvaliableMediatorServerAsyncActionCreator, updateAvaliableMediatorServerAsyncActionCreator } from '../actions/avaliableMediatorServersActions';
31 import { MediatorServer } from '../models/mediatorServer';
32 import { Typography } from '@mui/material';
33
34 export enum EditMediatorServerDialogMode {
35   None = "none",
36   AddMediatorServer = "addMediatorServer",
37   EditMediatorServer = "editMediatorServer",
38   RemoveMediatorServer = "removeMediatorServer",
39 }
40
41 const mapDispatch = (dispatcher: IDispatcher) => ({
42   addMediatorServer: (element: MediatorServer) => {
43     dispatcher.dispatch(addAvaliableMediatorServerAsyncActionCreator(element));
44   },
45   updateMediatorServer: (element: MediatorServer) => {
46     dispatcher.dispatch(updateAvaliableMediatorServerAsyncActionCreator(element));
47   },
48   removeMediatorServer: (element: MediatorServer) => {
49     dispatcher.dispatch(removeAvaliableMediatorServerAsyncActionCreator(element));
50   },
51 });
52
53 type DialogSettings = {
54   dialogTitle: string;
55   dialogDescription: string;
56   applyButtonText: string;
57   cancelButtonText: string;
58   readonly: boolean;
59 };
60
61 const settings: { [key: string]: DialogSettings } = {
62   [EditMediatorServerDialogMode.None]: {
63     dialogTitle: "",
64     dialogDescription: "",
65     applyButtonText: "",
66     cancelButtonText: "",
67     readonly: true,
68   },
69   [EditMediatorServerDialogMode.AddMediatorServer]: {
70     dialogTitle: "Add Mediator Server",
71     dialogDescription: "",
72     applyButtonText: "Add",
73     cancelButtonText: "Cancel",
74     readonly: false,
75   },
76   [EditMediatorServerDialogMode.EditMediatorServer]: {
77     dialogTitle: "Edit Mediator Server",
78     dialogDescription: "",
79     applyButtonText: "Update",
80     cancelButtonText: "Cancel",
81     readonly: false,
82   },
83   [EditMediatorServerDialogMode.RemoveMediatorServer]: {
84     dialogTitle: "Remove Mediator Server",
85     dialogDescription: "",
86     applyButtonText: "Remove",
87     cancelButtonText: "Cancel",
88     readonly: true,
89   },
90 };
91
92 type EditMediatorServerDialogComponentProps = Connect<undefined, typeof mapDispatch> & {
93   mode: EditMediatorServerDialogMode;
94   mediatorServer: MediatorServer;
95   onClose: () => void;
96 };
97
98 const urlRegex = RegExp("^https?://");
99
100 type EditMediatorServerDialogComponentState = MediatorServer & { errorMessage: string[] };
101
102 class EditMediatorServerDialogComponent extends React.Component<EditMediatorServerDialogComponentProps, EditMediatorServerDialogComponentState> {
103   constructor(props: EditMediatorServerDialogComponentProps) {
104     super(props);
105
106     this.state = {
107       ...this.props.mediatorServer,
108       errorMessage: []
109     };
110   }
111
112   areFieldsValid = () => {
113     return this.state.name.trim().length > 0 && this.state.url.trim().length > 0 && urlRegex.test(this.state.url);
114   }
115
116   createErrorMessages = () => {
117
118     let messages = [];
119     if (this.state.name.trim().length === 0 && this.state.url.trim().length === 0) {
120       messages.push("The server name and the url must not be empty.")
121     }
122     else
123       if (this.state.url.trim().length === 0) {
124         messages.push("The server url must not be empty.")
125
126       } else if (this.state.name.trim().length === 0) {
127         messages.push("The server name must not be empty.")
128       }
129
130     if (!urlRegex.test(this.state.url)) {
131       if (messages.length > 0) {
132         return messages.concat(["The server url must start with 'http(s)://'."])
133       } else {
134         return ["The server url must start with 'http(s)://'."]
135       }
136     }
137
138     return messages;
139   }
140
141
142
143   render(): JSX.Element {
144     const setting = settings[this.props.mode];
145
146     return (
147       <Dialog open={this.props.mode !== EditMediatorServerDialogMode.None}>
148         <DialogTitle id="form-dialog-title">{setting.dialogTitle}</DialogTitle>
149         <DialogContent>
150           <DialogContentText>
151             {setting.dialogDescription}
152           </DialogContentText>
153           {/* <TextField disabled spellCheck={false} autoFocus margin="dense" id="id" label="Id" type="text" fullWidth value={ this.state._id } onChange={(event)=>{ this.setState({_id: event.target.value}); } } /> */}
154           <TextField variant="standard" disabled={setting.readonly} spellCheck={false} margin="dense" id="name" label="Name" type="text" fullWidth value={this.state.name} onChange={(event) => { this.setState({ name: event.target.value }); }} />
155           <TextField variant="standard" disabled={setting.readonly} spellCheck={false} margin="dense" id="url" label="Url" type="text" fullWidth value={this.state.url} onChange={(event) => { this.setState({ url: event.target.value }); }} />
156
157           <Typography id="errorMessage" component={"div"} color="error">{this.state.errorMessage.map((error, index) => <div key={index}>{error}</div>)}</Typography>
158
159         </DialogContent>
160         <DialogActions>
161           <Button onClick={(event) => {
162
163             if (this.areFieldsValid()) {
164               this.setState({ errorMessage: [] });
165               this.onApply({
166                 id: this.state.id,
167                 name: this.state.name,
168                 url: this.state.url
169               });
170             } else {
171               const errorMessage = this.createErrorMessages()
172               this.setState({ errorMessage: errorMessage })
173             }
174
175             event.preventDefault();
176             event.stopPropagation();
177           }} color="inherit" > {setting.applyButtonText} </Button>
178           <Button onClick={(event) => {
179             this.onCancel();
180             this.setState({ errorMessage: [] });
181             event.preventDefault();
182             event.stopPropagation();
183           }} color="secondary"> {setting.cancelButtonText} </Button>
184         </DialogActions>
185       </Dialog>
186     )
187   }
188
189   private onApply = (element: MediatorServer) => {
190     this.props.onClose && this.props.onClose();
191     switch (this.props.mode) {
192       case EditMediatorServerDialogMode.AddMediatorServer:
193         element && this.props.addMediatorServer(element);
194         break;
195       case EditMediatorServerDialogMode.EditMediatorServer:
196         element && this.props.updateMediatorServer(element);
197         break;
198       case EditMediatorServerDialogMode.RemoveMediatorServer:
199         element && this.props.removeMediatorServer(element);
200         break;
201     }
202   };
203
204   private onCancel = () => {
205     this.props.onClose && this.props.onClose();
206   }
207
208   static getDerivedStateFromProps(props: EditMediatorServerDialogComponentProps, state: EditMediatorServerDialogComponentState & { _initialMediatorServer: MediatorServer }): EditMediatorServerDialogComponentState & { _initialMediatorServer: MediatorServer } {
209     if (props.mediatorServer !== state._initialMediatorServer) {
210       state = {
211         ...state,
212         ...props.mediatorServer,
213         _initialMediatorServer: props.mediatorServer,
214       };
215     }
216     return state;
217   }
218 }
219
220 export const EditMediatorServerDialog = connect(undefined, mapDispatch)(EditMediatorServerDialogComponent);
221 export default EditMediatorServerDialog;