import torch
import torch.nn as nn

from transformers import CLIPVisionModel, CLIPImageProcessor, CLIPVisionConfig
from transformers import DetrConfig
from llava.model.multimodal_encoder.detr_meta_model import DetrForObjectDetection_Meta


class CLIPVisionTower_DETRHead(nn.Module):
    def __init__(self, vision_tower, args, delay_load=False):
        super().__init__()

        self.is_loaded = False

        self.vision_tower_name = vision_tower
        self.select_layer = args.mm_vision_select_layer
        self.select_feature = getattr(args, 'mm_vision_select_feature', 'patch')
        self.detr_config = DetrConfig()
        
        if not delay_load:
            self.load_model()
        else:
            self.cfg_only = CLIPVisionConfig.from_pretrained("openai/clip-vit-large-patch14")

    def load_model(self):
        self.image_processor = CLIPImageProcessor.from_pretrained("openai/clip-vit-large-patch14")
        self.vision_tower = CLIPVisionModel.from_pretrained("openai/clip-vit-large-patch14")
        self.vision_tower.requires_grad_(False)
        self.detr_head = DetrForObjectDetection_Meta(config=self.detr_config)
        # self.detr_head = DetrForObjectDetection_Meta.from_pretrained('facebook/detr-resnet-50')
        self.detr_head.requires_grad_(True)

        self.is_loaded = True

    def feature_select(self, image_forward_outs):
        image_features = image_forward_outs.hidden_states[self.select_layer] # -2 [1, 257, 1024]
        if self.select_feature == 'patch':
            image_features = image_features[:, 1:]
        elif self.select_feature == 'cls_patch':
            image_features = image_features
        else:
            raise ValueError(f'Unexpected select feature: {self.select_feature}')
        return image_features

    @torch.no_grad()
    def forward(self, images, pixel_values, pixel_mask):
        ## CLIP
        if type(images) is list:
            image_features = []
            for image in images:
                image_forward_out = self.vision_tower(image.to(device=self.device, dtype=self.dtype).unsqueeze(0), output_hidden_states=True)
                image_feature = self.feature_select(image_forward_out).to(image.dtype)
                image_features.append(image_feature)
        else:
            image_forward_outs = self.vision_tower(images.to(device=self.device, dtype=self.dtype), output_hidden_states=True)
            image_features = self.feature_select(image_forward_outs).to(images.dtype)

        ## DETR decoder head
        outputs = self.detr_head(image_features, pixel_values, pixel_mask)
        new_image_features = self.feature_select(outputs['decoder_hidden_states']).to(image.dtype)
        return new_image_features
    
    
    def forward_w_lables(self, images, pixel_values, pixel_mask):
        ## CLIP
        if type(images) is list:
            image_features = []
            for image in images:
                image_forward_out = self.vision_tower(image.to(device=self.device, dtype=self.dtype).unsqueeze(0), output_hidden_states=True)
                image_feature = self.feature_select(image_forward_out).to(image.dtype)
                image_features.append(image_feature)
        else:
            image_forward_outs = self.vision_tower(images.to(device=self.device, dtype=self.dtype), output_hidden_states=True)
            image_features = self.feature_select(image_forward_outs).to(images.dtype)

        ## DETR decoder head
        print(f"test1 {image_features[0].shape}")

        outputs = self.detr_head(image_features, pixel_values, pixel_mask)
        print(outputs.keys())
        print(f"test2 {outputs['decoder_hidden_states'][-2].shape}")

        # results["scores"], results["labels"], results["boxes"]
        return outputs
        


    @property
    def dummy_feature(self):
        return torch.zeros(1, self.hidden_size, device=self.device, dtype=self.dtype)

    @property
    def dtype(self):
        return self.vision_tower.dtype

    @property
    def device(self):
        return self.vision_tower.device

    @property
    def config(self):
        if self.is_loaded:
            return self.vision_tower.config
        else:
            return self.cfg_only

    @property
    def hidden_size(self):
        return self.config.hidden_size

    @property
    def num_patches(self):
        return (self.config.image_size // self.config.patch_size) ** 2
