package com.altimetrik.ee.demo.tests;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import com.altimetrik.ee.demo.bean.Stocks;
import com.altimetrik.ee.demo.controller.StocksController;
import com.altimetrik.ee.demo.service.StocksService;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

@RunWith(SpringRunner.class)
@WebMvcTest({StocksController.class})
public class StocksControllerTest {

  @Autowired
  private MockMvc mockMvc;

  @MockBean
  StocksService stocksService;

  @Test
  public void getStocksByName() throws Exception {

    String str="2018-09-01 09:01:15";
    Timestamp timestamp= Timestamp.valueOf(str);

    List<Stocks> stocksList = Arrays.asList(
        new Stocks("HCL", "HCL Tech", timestamp, 420.0, "INR"),
        new Stocks("IBM", "IBM Tech", timestamp, 520.0, "USD"),
        new Stocks("UPY", "UPY Tech", timestamp, 520.0, "JPY")
    );

    List<String> queries = new ArrayList<>();
    queries.add("HCL");
    queries.add("IBM");

    when(stocksService.getStocksByIds(queries)).thenReturn(stocksList);

    mockMvc.perform(
            MockMvcRequestBuilders.get("/stocks/stockQuote?symbols=HCL,IBM"))
        .andExpect(status().isOk())
        .andExpect(content().json(JSON_STRING));
  }

  String JSON_STRING = "[{\"stockQuote\":\"HCL\",\"companyName\":\"HCL Tech\","
      + "\"date\":\"2018-09-01T03:31:15.000+0000\",\"price\":420.0,\"currency\":\"INR\"},"
      + "{\"stockQuote\":\"IBM\",\"companyName\":\"IBM Tech\",\"date\":\"2018-09-01T03:31:15.000+0000\","
      + "\"price\":520.0,\"currency\":\"USD\"},{\"stockQuote\":\"UPY\",\"companyName\":\"UPY Tech\","
      + "\"date\":\"2018-09-01T03:31:15.000+0000\",\"price\":520.0,\"currency\":\"JPY\"}]";

  @Test
  public void WhenNoParameterIsPassed() throws Exception {

    when(stocksService.getStocksByIds(any())).thenReturn(Collections.emptyList());

    mockMvc.perform(
            MockMvcRequestBuilders.get("/stocks/stockQuote?symbols="))
        .andExpect(status().isNoContent());
  }
}


