import React, { Component } from 'react';
import axios from 'axios';
import AccessDeniedV from './AccessDeniedV';
import EditableV from './EditableV';
import { Redirect } from 'react-router-dom';

class EditItemC extends Component {
	constructor(props) {
		super(props);
	}

	componentDidMount() {
	  axios.get("http://localhost:4000/api/item/" + this.props.match.params.itemId + "/edit")
	    .then(res => {
	    	let localSections = [];
	    	if(res.data.mtsections != null) {
		    	Object.keys(res.data.mtsections).map((key, index) => {
		    		localSections.push(res.data.mtsections[key]);
		    	})
	    	}
	      this.setState({
	      	itemInfo: res.data,
	      	itemTitle: res.data.mttitle,
	      	itemType: res.data.mttype,
	      	itemName: res.data.mtname,
	      	itemAssignee: res.data.mtassignee,
	      	itemPriority: res.data.mtpriority,
	      	itemDeadline: res.data.mtdeadline,
	      	sections: res.data.mtsections,
	      	filledSections: [...localSections]
	      });
	    })
	    .catch(err =>{
	    	this.setState({
	    		error: err.response.data.Error,
	    		exists: false
	    	})
	    })
	}

	onChangeGeneric = (i, event) => {
	  let valuesOfSections = [...this.state.filledSections]
	  valuesOfSections[i] = event.target.value
	  this.setState({
	    filledSections: valuesOfSections
	  })
	}

	onSubmitChanges = (event) => {
	  event.preventDefault()
    let dataobject = {}
    // for (let i = 0; i < this.state.filledSections.length; i++) {
    //   dataobject[this.state.sections[i]] = this.state.filledSections[i]
    // }
    Object.keys(this.state.sections).map((key, i) => {
    	dataobject[key] = this.state.filledSections[i]
    })
    let payload = {
    	mttitle: this.state.itemTitle,
    	mttype: this.state.itemType,
    	mtname: this.state.itemName,
    	mtassignee: this.state.itemAssignee,
    	mtpriority: this.state.itemPriority,
    	mtdeadline: this.state.itemDeadline,
    	mtsections: dataobject,
    	mtcontract: this.state.itemInfo.mtcontract,
    	mtlastuser: this.props.userKey,
    	mtuser: this.state.itemInfo.mtuser
    }
    console.log(dataobject);
	  let url = 'http://localhost:4000/api/item/' + this.state.itemInfo.mtkey + '/edit/submit';
	  //console.log(this.state.itemInfo.mtkey);
	  axios.put(url, payload)
	    .then(res => {
	    	this.setState({
	    		success: 'Item with contract ' + payload.mtcontract + ' successfully edited.'
	    	})
	    })
	    .catch(err => {
	    	console.log(err.response.data.Error);
	    	this.setState({
	    		error: err.response.data.Error
	    	})
	    })
	}

	onChangeTitle = (event) => {
	  this.setState({
	    itemTitle: event.target.value
	  })
	}

	onChangeAssignee = (event) => {
		this.setState({
			itemAssignee: event.target.value
		})
	}

	onChangePriority = (event) => {
		this.setState({
			itemPriority: event.target.value
		})
	}

	onChangeDeadline = (event) => {
		this.setState({
			itemDeadline: event.target.value
		})
	}

	roleCheck = (userRole) => {
		switch(userRole) {
			case "user":
				if(this.props.userKey != this.state.itemInfo["mtuser"] && this.props.userKey != this.state.itemInfo["mtassignee"]) {
					return <AccessDeniedV/>;
				} else {
					return <EditableV onSubmit={this.onSubmitChanges} generic={this.onChangeGeneric} filledSections={this.state.filledSections} item={this.state.itemInfo} titleChange={this.onChangeTitle} title={this.state.itemTitle} assigneeChange={this.onChangeAssignee} assignee={this.state.itemAssignee} priorityChange={this.onChangePriority} priority={this.state.itemPriority} deadlineChange={this.onChangeDeadline} deadline={this.state.itemDeadline}/>;
				}
				break;
			case "manager":
				console.log("manager here");
				return <EditableV onSubmit={this.onSubmitChanges} generic={this.onChangeGeneric} filledSections={this.state.filledSections} item={this.state.itemInfo} titleChange={this.onChangeTitle} title={this.state.itemTitle} assigneeChange={this.onChangeAssignee} assignee={this.state.itemAssignee} priorityChange={this.onChangePriority} priority={this.state.itemPriority} deadlineChange={this.onChangeDeadline} deadline={this.state.itemDeadline}/>;
				break;
			case "admin":
				console.log("admin here");
				return <EditableV onSubmit={this.onSubmitChanges} generic={this.onChangeGeneric} filledSections={this.state.filledSections} item={this.state.itemInfo} titleChange={this.onChangeTitle} title={this.state.itemTitle} assigneeChange={this.onChangeAssignee} assignee={this.state.itemAssignee} priorityChange={this.onChangePriority} priority={this.state.itemPriority} deadlineChange={this.onChangeDeadline} deadline={this.state.itemDeadline}/>;
				break;
			default:
				console.log("how");
		}
	}

	render() {
		if(this.state && this.state.success) {
			console.log('rendering success.')
			return (
				<Redirect
					to={{
						pathname:"/success",
						state: { success: this.state.success, linkToItem: '/viewItem/'+ this.state.itemInfo.mtkey}
					}}
				/>
			)
		}

		if(this.state && this.state.error) {
			if(!this.state.exists) {
				return (
					<Redirect
					  to={{
					    pathname: "/error",
					    state: { error: this.state.error}
					  }}
					/>
				)
			}
			return (
				<Redirect
				  to={{
				    pathname: "/error",
				    state: { error: this.state.error, referrer: this.props.location.pathname }
				  }}
				/>
			)
		}
		let properComponent;
		if(this.state && this.state.itemInfo) {
			properComponent = this.roleCheck(this.props.userRole);
		}
		return (
			<React.Fragment>
				<div>
				{
					this.state &&
					this.state.itemInfo &&
					properComponent
				}
				</div>
			</React.Fragment>
		);
	}
}

export default EditItemC;