package cn.bunny.pattern16;

import lombok.Data;
import lombok.Getter;

import java.util.HashMap;
import java.util.Map;

public class Behavior {
    public static void main(String[] args) {
        // 创建邮局
        PostOfficeImpl postOffice = new PostOfficeImpl();

        // 创建收信人和接收人
        Me me = new Me(postOffice, "在地球南边");
        You you = new You(postOffice, "在地球北边");

        // 到邮局建立联系
        postOffice.addPeople(me);
        postOffice.addPeople(you);

        // 我：
        me.sendLetter("我的消息", "You");
        System.out.println("---------------分隔线---------------");

        // 你：
        you.sendLetter("你的回信", "You");
        System.out.println("---------------分隔线---------------");

        // 我：
        me.sendLetter("哈哈哈哈哈哈哈哈哈", "You");
    }

    // 抽象中介者
    interface PostOffice {

        /**
         * 送信
         */
        void deliverLetter(String letter, String receiver);

        /**
         * 添加人
         */
        void addPeople(People people);
    }

    @Data
    static class PostOfficeImpl implements PostOffice {
        private final Map<String, People> peopleMap = new HashMap<>();

        /**
         * 送信
         */
        @Override
        public void deliverLetter(String letter, String receiver) {
            System.out.println("=>收信：邮局收到要寄的信");

            People people = peopleMap.get(receiver);

            System.out.println("=>送信：拿出地址查询收件人地址是：" + people.getAddress() + "，送信");
            System.out.println("=>收信人看信：");

            people.receiveLetter(letter);
        }

        /**
         * 添加人
         */
        @Override
        public void addPeople(People people) {
            peopleMap.put(people.getClass().getSimpleName(), people);
        }
    }


    @Getter
    static class People {
        private final String address;
        protected PostOffice postOffice;

        public People(PostOffice postOffice, String address) {
            this.postOffice = postOffice;
            this.address = address;
        }

        /**
         * 收到信
         *
         * @param letter 信的内容
         */
        public void receiveLetter(String letter) {
            System.out.println(letter);
        }

        /**
         * 发送信
         *
         * @param letter   信内容
         * @param receiver 收件人
         */
        public void sendLetter(String letter, String receiver) {
            postOffice.deliverLetter(letter, receiver);
        }
    }

    static class Me extends People {
        public Me(PostOffice postOffice, String address) {
            super(postOffice, address);
        }
    }

    static class You extends People {
        public You(PostOffice postOffice, String address) {
            super(postOffice, address);
        }
    }
}
