package com.nisum.mytime.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.nisum.mytime.exception.handler.MyTimeException;
import com.nisum.mytime.model.AccountInfo;
import com.nisum.mytime.service.AccountServiceImpl;
import com.nisum.mytime.utils.MyTimeUtils;

@RestController
@RequestMapping("/account")
public class AccountController {

	@Autowired
	private AccountServiceImpl accountServiceImpl;

	@RequestMapping(value = "/addAccount", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<AccountInfo> addAccount(@RequestBody AccountInfo accountInfo) throws MyTimeException {
		if (StringUtils.isEmpty(accountInfo.getAccountId())) {
			accountInfo.setAccountId(getAccountId());
		}
		accountInfo.setStatus(MyTimeUtils.ACTIVE);
		AccountInfo currentAccount = accountServiceImpl.addAccount(accountInfo);
		return new ResponseEntity<>(currentAccount, HttpStatus.OK);
	}

	// getting the account id.
	// accountid format is "Acc001"
	private String getAccountId() throws MyTimeException {
		return (MyTimeUtils.ACC_NAME + MyTimeUtils.ZERO_) + (accountServiceImpl.getAccounts().size() + MyTimeUtils.ONE);
	}

	@RequestMapping(value = "/getAccounts", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<List<Map<Object, Object>>> getAccounts() throws MyTimeException {
		List<Map<Object, Object>> acounts = accountServiceImpl.getAccountsList();
		return new ResponseEntity<>(acounts, HttpStatus.OK);
	}

	@RequestMapping(value = "/getAccountNames", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<List<String>> getAccountNames() throws MyTimeException {
		List<AccountInfo> acounts = accountServiceImpl.getAccounts();
		List<String> accountNames = new ArrayList<>();
		for (AccountInfo account : acounts) {
			accountNames.add(account.getAccountName());
		}
		return new ResponseEntity<>(accountNames, HttpStatus.OK);
	}

	@RequestMapping(value = "/deleteAccount", method = RequestMethod.DELETE, produces = MediaType.TEXT_PLAIN_VALUE)
	public ResponseEntity<String> deleteAccount(@RequestParam(value = "accountId") String accountId)
			throws MyTimeException {
		accountServiceImpl.deleteAccount(accountId);
		return new ResponseEntity<>("Success", HttpStatus.OK);
	}

}