package dev.peerat.framework;

import java.net.Socket;

import org.jose4j.jwt.consumer.InvalidJwtException;

public class Client<U extends User> extends Thread{

	private HttpReader reader;
	private HttpWriter writer;
	private Router<U> router;
	private Locker<Context> logger;

	public Client(Socket socket, Router<U> router) throws Exception{
		this.reader = new HttpReader(socket);
		this.writer = new HttpWriter(socket);
		this.router = router;
		this.logger = router.getLogger();
	}

	@Override
	public void run(){
		Context context = null;
		try{
			String[] headers = reader.readLine().split("\\s");
			reader.readHeaders();

			RequestType type = RequestType.valueOf(headers[0]);
			context = new Context(type, headers[1], isLogin(type, reader), writer, router.getDefaultHeaders(type));
			router.exec(context, reader, writer);
			writer.flush();
			writer.close();
		}catch(InvalidJwtException e){
		}catch(Exception e){
			e.printStackTrace();
			if(context != null && context.getResponseCode() == 0){
				try{
					context.response(500);
					writer.flush();
					writer.close();
				}catch(Exception ex){}
			}
		}
		if(context != null) logger.setValue(context);
	}

	private User isLogin(RequestType type, HttpReader reader) throws InvalidJwtException{
		String auth = reader.getHeader("Authorization");
		if(auth == null) return null;
		auth = auth.substring(7);
		try{
			return router.getUser(auth);
		}catch(InvalidJwtException e){
			try{
				writer.response(401, router.getDefaultHeaders(type));
				writer.flush();
				writer.close();
			}catch(Exception ex){}
			throw e;
		}
	}
}