package jp.agentec.abook.abv.bl.dto.comparator;

import java.util.Comparator;
import java.util.Date;

import jp.agentec.abook.abv.bl.acms.type.ContentSortingType;
import jp.agentec.abook.abv.bl.data.SortDirection;
import jp.agentec.abook.abv.bl.dto.ContentDto;

public class ContentDtoComparator implements Comparator<ContentDto> {
	private ContentSortingType contentSortingType;
	private SortDirection sortDirection;
	
	public ContentDtoComparator(ContentSortingType contentSortingType, SortDirection sortDirection) {
		this.contentSortingType = contentSortingType;
		this.sortDirection = sortDirection;
	}
	
	@Override
	public int compare(ContentDto dto1, ContentDto dto2) {
		int result = 0;
		
		switch (contentSortingType) {
			case ContentName:
				result = compareContentName(dto1.contentName, dto2.contentName);
				break;
			case ContentNameKana:
				result = compareContentNameKana(dto1.contentNameKana, dto2.contentNameKana);
				break;
			case DeliveryStartDate:
				result = compareDeliveryStartDate(dto1.deliveryStartDate, dto2.deliveryStartDate);
				break;
			case DownloadDate:
				break;
			case ReadingCount:
				break;
			case ReadingDate:
				break;
			case ContentSize:
				break;
			case ContentId:
				break;
			default:
				break;
		}
		
		return result;
	}

	private int compareContentName(String s1, String s2) {
        return compareTo(s1, s2);
	}
	
	private int compareContentNameKana(String s1, String s2) {
        return compareTo(s1, s2);
	}
	
	private int compareDeliveryStartDate(Date d1, Date d2) {

        return compareTo(d1, d2);
	}

    private int compareTo(Object obj1, Object obj2) {

        if (obj1 == null && obj2 == null) {
            return 0;
        }

        if (obj1 == null) {
            return -1;
        }

        if (obj2 == null) {
            return 1;
        }

        // obj1 != null && obj2 != null
        int result = 0;
        if (obj1 instanceof String && obj2 instanceof String) {
            String s1 = (String) obj1;
            String s2 = (String) obj2;
            result = s1.compareTo(s2);
        } else if (obj1 instanceof Date && obj2 instanceof Date) {
            Date s1 = (Date) obj1;
            Date s2 = (Date) obj2;
            result = s1.compareTo(s2);
        }

        if (sortDirection == SortDirection.DESC) {
            result *= -1;
        }

        return result;
    }
}
